package com.rfid.project.web;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.appframe.Menu;
import biz.appframe.MenuService;
import biz.appframe.Module;
import biz.appframe.ModuleService;
import biz.appframe.PageJsonBean;

import com.rfid.project.exception.CannotUpdateException;
import com.rfid.project.model.People;
import com.rfid.project.model.PositionAuthority;
import com.rfid.project.service.PositionAuthorityService;
import com.rfid.project.model.Position;
import com.rfid.project.service.PositionService;
import com.rfid.project.model.Authority;
import com.rfid.project.service.AuthorityService;

@Controller
public class PositionAuthorityController {

	private static final Logger logger = LoggerFactory
			.getLogger(PositionAuthorityController.class);

	@Autowired
	private PositionAuthorityService positionAuthorityService;

	@Autowired
	private PositionService positionService;

	@Autowired
	private AuthorityService authorityService;

	@Autowired
	private MenuService menuService;

	@Autowired
	private ModuleService moduleService;
	
	@RequestMapping(value = "/initMenu")
	public String initMenu(
			HttpServletRequest request, 
			HttpServletResponse response, 
			Model model) {
		HttpSession session = request.getSession();
		People people = (People) session.getAttribute("currentUser");
		if (null == people) {
			return "redirect:/login";
		}
		//通过权限获取菜单
		List<Menu> menus = null;
		List<Module> modules = null;
		if (people.getId() == 0) {
			modules = this.moduleService.findAll();
			menus = this.menuService.findAll();
		}else{
			menus = this.menuService.findMenuByAuthories((List<Authority>)session.getAttribute("powers"));
			modules = moduleService.findModuleByMenus(menus);
		}
		JSONArray jsonArray = new JSONArray();
		for (Module module : modules) {
			JSONObject mod = new JSONObject();
			mod.put("id", module.getId());
			mod.put("text", module.getName());
			
			JSONArray modelMenu = new JSONArray();
			for(Menu menu : menus){
				if (!module.getModuleCode().equals(menu.getModuleCode())) {
					continue;
				}
				JSONObject object = new JSONObject();
				object.put("id", menu.getId());
				object.put("text", menu.getName());
				
				JSONObject attr = new JSONObject();
				attr.put("url", menu.getCode());
				object.put("attributes", attr);
				
				modelMenu.add(object);
			}
			mod.put("children", modelMenu);
			
			jsonArray.add(mod);
		}
		PageJsonBean.printObject(response, jsonArray);
		return null;
	}

	@RequestMapping(value = "/positionAuthoritymgr")
	public String authoritymgr(HttpServletRequest request,
			HttpServletResponse response, 
			@RequestParam(value = "positionId", defaultValue = "") Long positionId,
			Model model) {
		//初始化模型
		initModelByPosition(positionId, model);
		
		return "positionAuthoritymgr";
	}

	private void initModelByPosition(Long positionId, Model model) {
		Position position = positionService.getPosition(positionId);
		
		if(position!=null){
			model.addAttribute("position", position);

			List<Authority> allAuthorities = authorityService.findAll();
			
			List<Authority> availableAuthorities = new ArrayList<Authority>();
			List<Authority> selectedAuthorities = positionAuthorityService.findAuthorityByPosition(position);
			
			for(Authority authority: allAuthorities){
				boolean founded = false;
				for(Authority s: selectedAuthorities){
					if(s.getId().equals(authority.getId())){
						founded = true;
						break;
					}
				}
				
				if(founded==false){
					availableAuthorities.add(authority);
				}
			}

			model.addAttribute("availableAuthorities", availableAuthorities);
			model.addAttribute("selectedAuthorities",selectedAuthorities);
		}
	}

	@RequestMapping(value = "/addPositionAuthority")
	public String addPositionAuthority(HttpServletRequest request,
			HttpServletResponse response, 
			@RequestParam(value = "positionId", defaultValue = "") Long positionId,
			@RequestParam(value = "availableIds") Long[] availableIds,
			Model model) {
		
		if(availableIds!=null){
			for(Long authorityId: availableIds){
				System.out.println("authorityId:"+authorityId);
			}
		}
		
		String[] testIds = request.getParameterValues("availableIds");
		if(testIds!=null){
			for(String id:testIds){
				System.out.println("testid:"+id);
			}
		}
		
		Position position = positionService.getPosition(positionId);
		if(position!=null && availableIds!=null){
			for(Long authorityId: availableIds){
				//删除原有的记录
				List<PositionAuthority> positionAuthorities = positionAuthorityService.findAll(position.getId(), authorityId, null);
				for(PositionAuthority p : positionAuthorities){
					positionAuthorityService.deletePositionAuthority(p.getId());
				}
				
				//增加新的记录
				Authority authority = authorityService.getAuthority(authorityId);
				PositionAuthority positionAuthority = new PositionAuthority();
				positionAuthority.setPosition(position);
				positionAuthority.setAuthority(authority);
				try {
					positionAuthorityService.savePositionAuthority(positionAuthority);
				} catch (CannotUpdateException e) {
					e.printStackTrace();
				}
			}
		}
		
		//初始化模型
		initModelByPosition(positionId, model);

		return "positionAuthoritymgr";

	}

	@RequestMapping(value = "/removePositionAuthority")
	public String removePositionAuthority(HttpServletRequest request,
			HttpServletResponse response, 
			@RequestParam(value = "positionId", defaultValue = "") Long positionId,
			@RequestParam(value = "selectedIds") Long[] selectedIds,
			Model model) {
		
		Position position = positionService.getPosition(positionId);
		if(position!=null && selectedIds!=null){
			for(Long authorityId: selectedIds){
				//删除原有的记录
				List<PositionAuthority> positionAuthorities = positionAuthorityService.findAll(position.getId(), authorityId, null);
				for(PositionAuthority p : positionAuthorities){
					positionAuthorityService.deletePositionAuthority(p.getId());
				}
				
				
				
			}
		}
		
		//初始化模型
		initModelByPosition(positionId, model);

		return "positionAuthoritymgr";
	}
	
	@RequestMapping(value = "/queryPositionAuthority")
	public String queryMenu(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "positionId", defaultValue = "") Long positionId,
			@RequestParam(value = "authorityId", defaultValue = "") Long authorityId,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<PositionAuthority> positionAuthoritys = positionAuthorityService
				.findAll(positionId, authorityId, pageNumber, pageSize, sort,
						order);
		JSONObject object = new JSONObject();
		object.put("total", positionAuthoritys.getTotalElements());
		JSONArray models = new JSONArray();
		for (PositionAuthority positionAuthority : positionAuthoritys) {
			JSONObject mod = new JSONObject();
			mod.put("id", positionAuthority.getId());
			mod.put("authorityID", positionAuthority.getAuthority().getId());
			mod.put("authorityName", positionAuthority.getAuthority().getName());
			mod.put("positionID", positionAuthority.getPosition().getId());
			mod.put("positionName", positionAuthority.getPosition().getName());

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}

	@RequestMapping(value = "/editPositionAuthority", method = RequestMethod.POST)
	public String editAuthority(HttpServletRequest request,
			HttpServletResponse response,
			@Valid PositionAuthority positionAuthority, Model model,
			RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			positionAuthorityService.savePositionAuthority(positionAuthority);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delPositionAuthority")
	public String delAuthority(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		this.positionAuthorityService.deletePositionAuthority(id);
		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		DateFormat dateFormat = com.rfid.project.util.DateUtil.getFormat();
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

}
